//
//  Networking.m
//  DouBan1.0
//
//  Created by Aurora on 15/11/26.
//  Copyright © 2015年 Aurora. All rights reserved.
//

#import "Networking.h"
#import <AFNetworking.h>
#import <ReactiveCocoa.h>
#import <objc/runtime.h>
#import "UtilsMacro.h"

@implementation Networking
//实现方法
+ (instancetype)sharedManager
{
    static dispatch_once_t onceToken;
    static Networking *instance;
    dispatch_once(&onceToken, ^{
        instance = [self manager];
        instance.requestSerializer = [[AFJSONRequestSerializer alloc]init];
        
    });
    return instance;
}

- (instancetype)init {
    return [[self class] sharedManager];
}

//分为6步
+ (void)receiveDataWithURLString:(NSString *)string method:(NSString *)method body:(NSString *)body Block:(Block)block {
    //1.将传归来的string 转成url
    NSURL *url = [NSURL URLWithString:string];
    //2.创建请求对象 request
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //3.设置请求方式Method
    [request setTimeoutInterval:10];
    [request setHTTPMethod:method];
    //4.判断需不需要拼接body,如果是post就需要拼接参数
    if ([method isEqualToString:@"POST"]) {
        NSData *data = [body dataUsingEncoding:NSUTF8StringEncoding];
        //5.如果是post 就拼接body部分
        [request setHTTPBody:data];
    }
    //6.建立链接
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *  response, NSData *  data, NSError *  connectionError) {
        //安全
        if (data != nil) {
            //调用block 将data对象传值
            block(data);
        }
        
        
    }];
    
    
    
}
- (RACSignal *)requestGetWithUrlString:(NSString *)urlString {
    NSString *formatURl = F(@"%@%@", APIServer,urlString);
    NSString *encodingString = [formatURl stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    return [[self requestGetReturnJSONWithUrlString:encodingString]map:^id(RACTuple *value) {
        return [value first];
    }];
}

- (RACSignal *)requestGetReturnJSONWithUrlString:(NSString *)urlString {
    return [[[self rac_GET:urlString parameters:nil]catch:^RACSignal *(NSError *error) {
        NSError *er = [[NSError alloc]initWithDomain:@"ErrorDomain" code:999999 userInfo:@{@"message":@"请检查网络连接"}];
        return [RACSignal error:er];
    }]flattenMap:^RACStream *(id value) {
        NSDictionary *json = [value first];
        return [RACSignal return:[RACTuple tupleWithObjectsFromArray:@[json]]];
    }];
}




+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString;
{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err)
    {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}



@end
